package models

import (
	"time"

	"gorm.io/gorm"
)

type Author struct {
	Model

	Name       string `json:"name"`
	Department string `json:"department"`
	PhoneNo    string `json:"phone_no"`
	Age        int    `json:"age"`
	Gender     int    `json:"gender"`
}

// 作者是否存在
func ExistAuthorByID(id int) (bool, error) {
	var author Author
	err := db.Select("id").Where("id = ? ", id).First(&author).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, nil
	}

	if author.ID > 0 {
		return true, nil
	}

	return false, nil
}

// 查询作者总数
func GetAuthorTotal(maps interface{}) (int64, error) {
	var count int64
	if err := db.Model(&Author{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

// 根据id查询作者
func GetAuthor(id int) (*Author, error) {
	var author Author
	err := db.Model(&Author{}).Where("id = ? ", id).First(&author).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &author, nil
}

// 根据id查询文章
func GetAuthors(pageNum int, pageSize int, maps interface{}) ([]*Author, error) {
	var authors []*Author
	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&authors).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return authors, nil
}

// 添加作者
func AddAuthor(data map[string]interface{}) error {
	author := Author{
		Name:       data["name"].(string),
		Department: data["department"].(string),
		PhoneNo:    data["phone_no"].(string),
		Gender:     data["gender"].(int),
		Age:        data["age"].(int),
	}
	if err := db.Create(&author).Error; err != nil {
		return err
	}
	return nil
}

// 修改作者
func EditAuthor(id int, data interface{}) error {
	if err := db.Model(&Author{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}
	return nil
}

func DeleteAuthor(id int) error {
	if err := db.Where("id = ?", id).Delete(&Author{}).Error; err != nil {
		return err
	}
	return nil
}

// 添加作者前添加时间
func (author *Author) BeforeCreate(tx *gorm.DB) error {
	tx.Model(author).Where("id = ?", author.ID).Update("CreatedOn", time.Now().Unix())

	return nil
}

// 使用Unscoped()物理删除数据
func CleanAllAuthor() error {
	if err := db.Unscoped().Where("deleted_on != ?", nil).Delete(&Author{}).Error; err != nil {
		return err
	}
	return nil
}
